<?php

namespace App\Http\Controllers\Index;

use App\Http\Controllers\Controller;
use App\Models\Course;
use App\Models\Resource;
use App\Services\AliVodService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CourseController extends Controller
{
    //课程首页
    public function index(Course $course){
        $data = [
            'course' => $course,
        ];
        return view('index.course.index',$data);
    }

    // 课程阅读页
    public function resource(Course $course,Resource $resource){
        $data = [
            'course'=>$course,
            'resource'=>$resource,
        ];
        return view('index.course.resource',$data);
    }
    
    // 获取阿里云视频播放凭证
    public function getVideoPlayAuth(Request $request)
    {
        try {
            Log::info('获取视频播放凭证请求', ['request' => $request->all()]);
            
            $videoId = $request->input('videoId');
            if (empty($videoId)) {
                Log::warning('视频ID为空');
                return response()->json([
                    'code' => 0, 
                    'msg' => '视频ID不能为空', 
                    'detail' => '请确保传入了有效的视频ID'
                ]);
            }
            
            // 创建AliVodService实例
            $vodService = new AliVodService();
            
            // 首先验证阿里云VOD配置
            $configTest = $vodService->validateConfig();
            if (!$configTest['status']) {
                Log::error('阿里云VOD配置验证失败', $configTest);
                
                // 返回更详细的错误信息
                $errorMsg = '阿里云视频点播服务配置错误';
                $errorDetails = $configTest['errors'];
                
                // 判断是否是SDK未安装导致的错误
                $sdkNotInstalled = false;
                foreach ($errorDetails as $error) {
                    if (strpos($error, 'SDK未安装') !== false) {
                        $sdkNotInstalled = true;
                        break;
                    }
                }
                
                if ($sdkNotInstalled) {
                    $errorMsg = '服务器未安装阿里云SDK';
                    $actionRequired = '请联系管理员安装阿里云SDK: composer require alibabacloud/sdk';
                    $errorDetails[] = $actionRequired;
                }
                
                return response()->json([
                    'code' => 0, 
                    'msg' => $errorMsg, 
                    'details' => $errorDetails,
                    'sdk_missing' => $sdkNotInstalled
                ]);
            }
            
            // 获取播放凭证
            $playAuth = $vodService->getPlayAuth($videoId);
            
            // 检查播放凭证是否获取成功
            if (empty($playAuth)) {
                Log::error('获取播放凭证失败', ['videoId' => $videoId]);
                return response()->json([
                    'code' => 0, 
                    'msg' => '获取播放凭证失败', 
                    'details' => [
                        '可能的原因：',
                        '1. 视频ID不存在或已删除',
                        '2. 阿里云服务暂时不可用',
                        '3. 阿里云账号没有权限访问该视频',
                        '4. 服务器网络连接阿里云异常'
                    ]
                ]);
            }
            
            // 记录成功日志
            Log::info('获取播放凭证成功', [
                'videoId' => $videoId, 
                'playAuthLength' => strlen($playAuth)
            ]);
            
            // 返回成功响应
            return response()->json([
                'code' => 1, 
                'data' => [
                    'PlayAuth' => $playAuth,
                    'VideoId' => $videoId
                ]
            ]);
        } catch (\Exception $e) {
            // 记录详细错误日志
            Log::error('获取播放凭证异常', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            
            // 向前端返回友好的错误信息
            return response()->json([
                'code' => 0, 
                'msg' => '视频服务暂时不可用，请稍后再试',
                'error' => $e->getMessage()
            ]);
        }
    }

    /**
     * 测试阿里云VOD连接
     * @return \Illuminate\Http\JsonResponse
     */
    public function testVodConnection()
    {
        try {
            // 创建AliVodService实例
            $vodService = new AliVodService();
            
            // 获取SDK安装状态
            $sdkInstalled = class_exists('\\AlibabaCloud\\Client\\AlibabaCloud');
            
            // 获取配置验证结果
            $configTest = $vodService->validateConfig();
            
            return response()->json([
                'sdk_installed' => $sdkInstalled,
                'sdk_version' => $sdkInstalled ? '已安装' : '未安装',
                'config_status' => $configTest['status'],
                'config_errors' => $sdkInstalled ? $configTest['errors'] : ['阿里云SDK未安装，无法验证配置']
            ]);
        } catch (\Exception $e) {
            Log::error('测试VOD连接异常', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'sdk_installed' => false,
                'config_status' => false,
                'error' => $e->getMessage()
            ]);
        }
    }
}
